package com.hmall.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.hmall.search.domain.po.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class ItemSyncListener {
    @Autowired
    private ElasticsearchClient esClient;
    /**
     * 监听增加或修改
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.save.sync.queue",
                    arguments={@Argument(name="x-single-active-consumer",
                            value = "true", type = "java.lang.Boolean") }),
            exchange = @Exchange(value = "item.sync.exchange",type = ExchangeTypes.DIRECT),
            key = "item.save.sync"),
            concurrency = "1"
    )
    public void saveSyncListener(List<ItemDoc> itemDocs) throws IOException {
        for (ItemDoc itemDoc : itemDocs) {
            esClient.index(builder->builder
                    .index("items")
                    .id(itemDoc.getId())
                    .document(itemDoc));
            log.info("保留商品文档：{}",itemDoc);
        }
    }
    /**
     * 监听删除
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.remove.sync.queue",
                    arguments={@Argument(name="x-single-active-consumer",
                            value = "true", type = "java.lang.Boolean") }),
            exchange = @Exchange(value = "item.sync.exchange", type = ExchangeTypes.DIRECT),
            key = "item.remove.sync"),
            concurrency = "1"
    )
    public void listenItemRemoveSync(Long itemId) throws IOException {
        esClient.delete(builder->builder.index("items").id(itemId.toString()));
        log.info("删除商品文档，id={}", itemId);
    }
}
